package com.leetcode.Offer;

public class JZ29 {
    public int[] spiralOrder(int[][] matrix) {

        //参考官方解题思路：按层模拟
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[]{};
        }
        int top = 0;
        int left = 0;
        int right = matrix[0].length - 1;
        int bottom = matrix.length - 1;

        int[] ints = new int[(right + 1) * (bottom + 1)];
        int index = 0;

        while (top <= bottom && right >= left) {
            for (int i = left; i <= right; i++) {//上
                ints[index++] = matrix[top][i];
            }
            for (int i = top + 1; i <= bottom; i++) {//右
                ints[index++] = matrix[i][right];
            }
            if (left < right && top < bottom) {//很有必要的条件
                for (int i = right - 1; i >= left + 1; i--) {//下
                    ints[index++] = matrix[bottom][i];
                }
                for (int i = bottom; i >= top + 1; i--) {//左
                    ints[index++] = matrix[i][left];
                }
            }
            top++;
            left++;
            right--;
            bottom--;
        }
        return ints;
    }
}
